<template>
	<view>
		<map id="map" ref="map" :longitude="longitude" :latitude="latitude" :scale="mapScale" style="width: 100vw;"
			:style="{ height: app.globalData.sysInfo.windowHeight + 'px' }" :circles="circles" :markers="markers" :polygons="polygons"
			@markertap="markerclick" @tap="tap" :enable-scroll="!popupOpenState" subkey="AM4BZ-UGEKQ-F355S-2PJVY-46UEO-ZXBDD" layer-style="1">
		</map>

		<!-- 顶部阴影 -->
		<view class="bck-top">
			<image style="width: 100%;" src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/bck-top.png" mode="widthFix"></image>
		</view>
		<!-- 底部阴影 -->
		<view class="bck-bottom">
			<image style="width: 100%;" src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/bck-bottom.png" mode="widthFix"></image>
		</view>

		<!-- 当前定位城市 -->
		<view class="city-position">
			<image src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/city-position.png" mode="widthFix"></image>
			<text style="margin-left: 5px;">{{positionCity}}</text>
		</view>

		<!-- 右侧菜单 -->
		<view class="tabbar-right">
			<view @click="openPopupSetSystem">
				<image src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/set.png" mode="widthFix"></image>
			</view>
			<view @click="openPopupShare">
				<image src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/my/icon-邀请好友.png" mode="widthFix"></image>
			</view>
			<view @click="scanQRCode">
				<image src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/scan.png" mode="widthFix"></image>
			</view>
			<view @click="switchPageCoinType">
				<image :src="'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/' + (curPageCoinType > 1 ? 'gold.png' : 'copper.png')" mode="widthFix"></image>
			</view>
		</view>

		<!-- 底部菜单 -->
		<view class="tabbar-bottom">
			<view class="group" style="justify-content: flex-end;">
				<view class="item" @click="openPopupTask">
					<image class="logo" src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/logo.png" mode="heightFix"></image>
					<image style="width: 25px;" src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/tabbar-icon1.png" mode="widthFix"></image>
				</view>
			</view>
			<view class="group" style="justify-content: center;">
				<view @click="myPosition" class="item">
					<image src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/tabbar-icon2.png" mode="widthFix"></image>
				</view>
			</view>
			<view class="group" style="justify-content: flex-start;">
				<view @click="goMy" class="item">
					<image src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/tabbar-icon3.png" mode="widthFix"></image>
				</view>
			</view>

		</view>
		
		<!-- 弹窗：设置 -->
		<popup-setsystem ref="pSetsystem" @close="publicClose"></popup-setsystem>
		<block v-if="JSON.stringify(app.globalData.userinfo) !== '{}'">
			<!-- 弹窗：悬赏、赏金任务 -->
			<popup-task ref="pTask" @close="publicClose"></popup-task>

			<!-- 弹窗：邀请好友 -->
			<popup-share ref="pShare" @close="publicClose"></popup-share>

			<!-- 弹窗：踪迹 -->
			<popup-trace ref="pTrace" @close="traceClose"></popup-trace>

			<!-- 弹窗：找到宝藏 -->
			<popup-findcoin ref="pFindcoin" @close="publicClose" :coinId="findCoinInfo.id" :coinType="findCoinInfo.type" :coinName="findCoinInfo.name" :coinAddress="findCoinInfo.address"></popup-findcoin>
			
			<!-- 弹窗：查看视频 -->
			<popup-findvideo ref="pFindvideo" @close="publicClose"></popup-findvideo>
		</block>
	</view>

</template>
<script>
// #ifdef MP-WEIXIN
export default {
  onShareAppMessage() {
    return {
		title: '快来一起寻宝吧～',
		imageUrl: 'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/jinxiangguo-share.jpeg',
		path: '/pages/game/game'
	}
  }
}
// #endif
</script>
<script setup>
	const app = getApp()
	import {
		ref,
		computed,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		jsonp
	} from 'vue-jsonp'
	const { proxy } = getCurrentInstance() // 全局对象

	// ref组件
	const pTask = ref() // 赏金、悬赏任务弹窗
	const pShare = ref() // 签到弹窗
	const pSetsystem = ref() // 设置弹窗
	const pTrace = ref() // 踪迹弹窗
	const pFindcoin = ref() // 找到宝藏弹窗
	const pFindvideo = ref() // 查看视频弹窗
	const mapContext = ref()
	
	const popupOpenState = ref(false)
	
	const userInfo = ref(app.globalData.userinfo)
	// 找到宝藏
	const findCoinInfo = ref({}) // 硬币信息

	// 当前地图类型，1金币，2银币与铜币
	const curPageCoinType = ref(2)
	// 关于地图贴片
	const curClickMarkerId = ref(0)
	
	const positionCity = ref('正在定位')
	const longitude = ref(121.472644) // 我的定位 经度
	const latitude = ref(31.231706) // 我的定位 纬度
	const myPositionMarker = ref({}) // 我的位置 marker标记
	const mapScale = ref(13)
	const isShanghai = ref(false) // 是否在上海
	const markers = ref([]); // 铜币、金币的贴图
	const polygons = ref([]); // 金币的六边形
	var coinMapList = [] // 银币与铜币列表
	var coinGoldMapList = [] // 金币列表
	var circlesTmp = [] // circle根据scale级别会隐藏
	const circles = ref([])
	
	let isGoldFalse = true; // 金币列表是否还存在假金币
	
	onLoad(async (options) => {
		// #ifdef H5
		if (!app.globalData.token) {
			uni.redirectTo({
				url: '/pages/index/index'
			})
			return
		}
		if (proxy.$wx && app.isWechat()) {
			app.wxinit()
		}
		// #endif
		// #ifdef MP-WEIXIN
		await app.globalData.loginPromise // 等待登录完毕
		if (app.globalData.token && (('scene' in options) || app.globalData.helpCode)) {
			if (!app.globalData.helpCode) app.globalData.helpCode = options.scene
			app.doHelp() // 直接助力
		} else if ('scene' in options) {
			app.globalData.helpCode = options.scene
		}
		// #endif
		mapContext.value = uni.createMapContext('map', this)
		uni.getLocation({
			type: 'gcj02',
			altitude: true,
			isHighAccuracy: true,
			success(res) {
				if (app.globalData.token) {
					loadData()
				}
				myPositionMarker.value = {longitude: res.longitude, latitude: res.latitude}
				// positionCity.value = '上海市'
			},
			fail(err) {
				console.error(err)
				if (app.globalData.token) {
					loadData()
				}
			}
		})
		
	})
	/**
	 * 加载所有硬币信息
	 */
	const loadData = (hideLoading = false) => {
		// 请求硬币列表
		let data = {}
		if (curPageCoinType.value === 1) {
			coinGoldMapList = []
			data.type = curPageCoinType.value
		} else {
			coinMapList = []
		}
		uni.request({
			url: app.globalData.requestUrl + '/api/coin/list',
			header: {
				'Authorization': 'Bearer ' + app.globalData.token
			},
			data: data,
			success: (res) => {
				if (res.data.code === 200) {
					console.log(res.data.data)
					// 对硬币进行分类
					if (curPageCoinType.value === 1) {
						coinGoldMapList = res.data.data.list;
						isGoldFalse = res.data.data.is_false;
					} else {
						coinMapList = res.data.data
					}
					positionCity.value = '上海市'
					calcMapMarkers() // 去计算markers该怎么放
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			},
			complete() {
				if (hideLoading) uni.hideLoading()
			}
		})
	}
	/**
	 * 摆放地图markers
	 */
	const calcMapMarkers = () => {
		if (!app.globalData.isReloadMarkers) return
		
		let list = coinMapList
		if (curPageCoinType.value === 1) {
			list = coinGoldMapList // 当前是金币视角
			
		}
		let tmpMarkers = [],
			tmpCircles = [];
		
		const tmpPolygons = [];
		for (let i = 0; i < list.length; i++) {
			let coin = list[i]
			if (coin.latitude < -90 || coin.latitude > 90) continue // 容错：经纬度填反
			
			if (curPageCoinType.value === 1 && coin.is_unlock === 0) {
				tmpPolygons.push(coin.polygon);
			} else {
				const icon = coin.type === 2
					? coin.is_unlock === 1 ? 'unlock-icon-red.png' : 'silver.png'
					: coin.type === 1 ? 'unlock-icon-gold.png'
					: coin.is_unlock === 1 ? 'unlock-icon-yellow.png'
					: 'copper.png';
				
				let data = {
					id: coin.id,
					longitude: coin.longitude,
					latitude: coin.latitude,
					anchor: {x: .5, y: .5},
					iconPath: 'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/' + icon,
					width: coin.type === 1 ? 49 : 37,
					height: coin.type === 1 ? 43 : 35,
				};
				if (curPageCoinType.value !== 1 && coin.is_unlock === 1) {
					data.width = 20;
					data.height = 28;
				}
				tmpMarkers.push(data);
				
				if (coin.radius === 0 || coin.is_unlock === 1) continue;
				tmpCircles.push({
					id: coin.id,
					longitude: coin.longitude,
					latitude: coin.latitude,
					fillColor: '#FFFFFFA3',
					color: '#B1CCCB',
					strokeWidth: 2,
					radius: coin.radius
				});
			}
		}
		tmpMarkers.unshift({
			id: 999999999,
			longitude: myPositionMarker.value.longitude,
			latitude: myPositionMarker.value.latitude,
			iconPath: "https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/myposition.png",
			width: 49,
			height: 68
		}) // 我的位置
		console.log(tmpMarkers)
		markers.value = tmpMarkers;
		polygons.value = tmpPolygons;
		console.log('当前polygons', tmpPolygons);
		app.globalData.isReloadMarkers = false
		circles.value = tmpCircles
	}
	
	// 切换地图类型
	const switchPageCoinType = () => {
		app.globalData.isReloadMarkers = true
		if (curPageCoinType.value === 1) {
			uni.showToast({
				title: '已切换为银币、铜币视角',
				icon: 'none'
			})
			curPageCoinType.value = 2
			calcMapMarkers() // 重新计算地图markers
		} else {
			curPageCoinType.value = 1
			if (coinGoldMapList.length === 0) {
				// 请求金币
				uni.showLoading({
					title: '切换为金币视角'
				})
				mapScale.value = 12
				loadData(true)
			} else {
				uni.showToast({
					title: '已切换为金币视角',
					icon: 'none'
				})
				calcMapMarkers() // 重新计算地图markers
			}
		}
		
	}
	
	// 去“我的”页面
	const goMy = () => {
		// #ifdef MP-WEIXIN
		if (!app.globalData.token) {
			uni.navigateTo({
				url: '/pages/index/index'
			})
			return
		}
		// #endif
		uni.navigateTo({
			url: '/pages/my/my'
		})
	}
	// 定位我的位置
	const myPosition = () => {
		app.playAudio() // 点击音效
		// if (isShanghai.value) {
			let scaleTarget = 13;
			mapContext.value.getScale({
				success(res) {
					if (mapScale.value === scaleTarget && res.scale !== scaleTarget) {
						mapScale.value = scaleTarget + 0.1;
					} else {
						mapScale.value = scaleTarget;
					}
				}
			});
			uni.getLocation({
				type: 'gcj02',
				altitude: true,
				isHighAccuracy: true,
				success(res) {
					longitude.value = res.longitude
					latitude.value = res.latitude
					mapContext.value.moveToLocation({
						longitude: res.longitude,
						latitude: res.latitude,
						success(res2) {
							const tmp = {
								id: 999999999,
								longitude: res.longitude,
								latitude: res.latitude,
								iconPath: "https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/game/myposition.png",
								width: 49,
								height: 68
							};
							markers.value[0] = tmp;
						}
					})
				},
				fail(err) {
					console.log('定位错误', err)
				}
			})
		// } else {
		// 	uni.showToast({
		// 		title: '您的定位不在上海，无法定位',
		// 		icon: 'none'
		// 	})
		// }
	}
	
	const getDistance = (lat1, lon1, lat2, lon2) => {
	  const R = 6378137; // 地球半径（米）
	  const rad = Math.PI / 180;
	  const dLat = (lat2 - lat1) * rad;
	  const dLon = (lon2 - lon1) * rad;
	
	  const a = Math.sin(dLat / 2) ** 2 +
	            Math.cos(lat1 * rad) * Math.cos(lat2 * rad) *
	            Math.sin(dLon / 2) ** 2;
	
	  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	  return R * c;
	}
	
	// 点击地图任意位置，适用于金币模式
	const tap = (e) => {
		if (curPageCoinType.value !== 1) return;
		const gold = coinGoldMapList.find(function(item) {
		  return getDistance(item.latitude, item.longitude, e.detail.latitude, e.detail.longitude) <= item.radius
		});
		if (!gold) return;
		popupOpenState.value = true;
		pTrace.value.open(gold, isGoldFalse);
	}
	// 点击marker，弹出踪迹弹窗
	const markerclick = (e) => {
		console.log('e1', e);
		app.playAudio() // 点击音效
		// #ifdef MP-WEIXIN
		if (!app.globalData.token) {
			uni.navigateTo({
				url: '/pages/index/index'
			})
			return
		}
		// #endif
		const gold = coinGoldMapList.find(function(item) {
		  return item.id === e.detail.markerId
		})
		if (gold) {
			uni.showToast({
				title: '该金币已被找到',
				icon: 'none'
			});
		} else {
			const curcoin = coinMapList.find(function(item) {
			  return item.id === e.detail.markerId
			})
			if (!curcoin) return
			popupOpenState.value = true;
			console.log(curcoin);
			let scaleTarget = 15;
			if (curcoin.type === 3) {
				scaleTarget = 17;
			}
			mapContext.value.getScale({
				success(res) {
					if (res.scale < scaleTarget) {
						if (mapScale.value === scaleTarget) {
							mapScale.value = scaleTarget + 0.1;
						} else {
							mapScale.value = scaleTarget;
						}
					}
					// #ifdef H5
					mapContext.value.moveToLocation({
						longitude: e.detail.longitude,
						latitude: e.detail.latitude
					});
					// #endif
					// #ifdef MP-WEIXIN
					const curmarker = markers.value.find(function(item) {
					  return item.id === e.detail.markerId
					})
					mapContext.value.moveToLocation({
						longitude: Number(curmarker.longitude),
						latitude: Number(curmarker.latitude),
						success() {
							console.log('移动成功')
						},
						fail(err) {
							console.log('移动失败', err)
						}
					});
					// #endif
				}
			});
			
			if (curcoin.is_unlock === 1) {
				pFindvideo.value.open(curcoin)
			} else {
				pTrace.value.open(curcoin)
			}
		}
		
	}
	// 踪迹弹窗的监听窗口，可能需要更新页面进行缩圈
	const traceClose = (res) => {
		popupOpenState.value = false
		if (app.globalData.isReloadMarkers) {
			if (res === 1) {
				uni.showLoading({
					title: '正在刷新金币'
				})
			} else {
				uni.showLoading({
					title: '硬币范围正在缩小'
				})
			}
			
			loadData(true)
		}
	}
	// 公共关闭弹窗事件，允许页面滑动
	const publicClose = () => {
		popupOpenState.value = false
	}
	// 微信扫一扫
	const scanQRCode = () => {
		// #ifdef H5
		if (proxy.$wx && app.isWechat()) {
			proxy.$wx.scanQRCode({
				needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
				success: function(res) {
					var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
					let data = JSON.parse(result)
					uni.showLoading()
					uni.request({
						url: app.globalData.requestUrl + '/api/coin/getCoinInfo',
						header: {
							'Authorization': 'Bearer ' + app.globalData.token
						},
						data: data,
						success: (res) => {
							console.log(res.data)
							uni.hideLoading();
							if (res.data.code === 200) {
								findCoinInfo.value = res.data.data
								pFindcoin.value.open() // 发现硬币，进入认领流程
							} else {
								//说明参数不合法
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								})
							}
						},
						fail: () => {
							uni.hideLoading()
						}
					})
				},
				fail: function(err) {
					console.log(err)
				}
			})
		} else {
			uni.showToast({
				title: '使用扫一扫功能，请在微信客户端打开本页面',
				icon: 'none'
			})
		}
		// #endif
		// #ifdef MP-WEIXIN
		uni.scanCode({
			scanType: 'qrCode',
			success: function (res) {
				let data = JSON.parse(res.result)
				uni.showLoading()
				uni.request({
					url: app.globalData.requestUrl + '/api/coin/getCoinInfo',
					header: {
						'Authorization': 'Bearer ' + app.globalData.token
					},
					data: data,
					success: (res) => {
						uni.hideLoading();
						console.log(res.data)
						if (res.data.code === 200) {
							findCoinInfo.value = res.data.data
							pFindcoin.value.open() // 发现硬币，进入认领流程
						} else {
							//说明参数不合法
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					fail: () => {
						uni.hideLoading()
					}
				})
			}
		});
		// #endif

	}
	// 打开赏金任务弹窗
	const openPopupTask = () => {
		app.playAudio() // 点击音效
		// #ifdef MP-WEIXIN
		if (!app.globalData.token) {
			uni.navigateTo({
				url: '/pages/index/index'
			})
			return
		}
		// #endif
		popupOpenState.value = true
		pTask.value.open()
	}
	// 打开邀请好友弹窗
	const openPopupShare = () => {
		app.playAudio()
		pShare.value.open()
	}
	// 打开系统设置弹窗
	const openPopupSetSystem = () => {
		app.playAudio()
		popupOpenState.value = true
		pSetsystem.value.open()
	}
	// 打开踪迹弹窗
	const openPopupTrace = () => {
		app.playAudio()
		// #ifdef MP-WEIXIN
		if (!app.globalData.token) {
			uni.navigateTo({
				url: '/pages/index/index'
			})
			return
		}
		// #endif
		popupOpenState.value = true
		pTrace.value.open()
	}
	
</script>
<!--这里引入分离的界面样式代码-->
<style scoped>
	@import './game.css';
</style>